package com.dm.utils;


import com.dm.common.Const;
import com.dm.common.enums.ResponseCode;
import com.dm.dto.input.FileDto;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author hqw521@qq.com
 * @date 2018/12/12 19:03
 */
public class FileUtil {
    /**
     * 文件上传
     *
     * @param file       文件
     * @param serverPath 服务器路径
     * @param path       文件路径
     * @return 文件绝对路径和文件相对路径
     */
    public static Map<String, String> upload(MultipartFile file, String serverPath, String path) {
        // 文件扩展名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = generateFileName(extension);
        // 相对路径
        String relativePath = path + fileName;

        // 实际路径
        String realPath = serverPath + relativePath;

        Map<String, String> map = new HashMap<>(2);

        Client client = new Client();
        WebResource resource = client.resource(realPath);

        try {
            resource.put(String.class, file.getBytes());
            map.put("relativePath", relativePath);
            map.put("realPath", realPath);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
            return map;
        }
    }

    /**
     * 创建文件
     *
     * @param extension  文件扩展名
     * @param serverPath 服务器IP
     * @param path       文件路径
     * @return 文件绝对路径和文件相对路径
     */
    public static Map<String, String> createFile(String extension, String serverPath, String path) {
        String fileName = generateFileName(extension);
        // 相对路径
        String relativePath = path + fileName;

        // 实际路径
        String realPath = serverPath + relativePath;

        Client client = new Client();
        WebResource resource = client.resource(realPath);
        resource.put(String.class, fileName);

        Map<String, String> map = new HashMap<>(2);
        map.put("relativePath", relativePath);
        map.put("realPath", realPath);

        return map;
    }

    /**
     * 文件删除
     *
     * @param filePath 文件路径
     * @return "SUCCESS" 或 "ERROR"
     */
    public static String delete(String filePath) {
        try {
            Client client = new Client();
            WebResource resource = client.resource(filePath);

            resource.delete();
            return ResponseCode.SUCCESS.getDesc();
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseCode.ERROR.getDesc();
        }
    }

    public static InputStream download(String filePath) {
        try {
            // 发起URL请求，获取连接对象
            URL httpUrl = new URL(filePath);
            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            // 建立连接
            connection.connect();
            // 获取资源输入流
            InputStream inputStream = connection.getInputStream();

            return inputStream;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据时间生成名字，防止重名
     *
     * @return 名字
     */
    public static String generateName() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String formatDate = format.format(date);
        String str = "";
        for (int i = 0; i < 5; i++) {
            int n = (int) (Math.random() * 90) + 10;
            str += n;
        }
        return formatDate + str;
    }

    /**
     * 压缩文件
     */
    public static InputStream compressFileToZip(List<FileDto> fileDtos) {
        InputStream inputStream = null;
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(new DataOutputStream(bout));
            int len;
            byte[] buf = new byte[1024];
            for (FileDto fileDto : fileDtos) {
                InputStream input = FileUtil.download(Const.uploadHost + fileDto.getRelativePath());
                zipOutputStream.putNextEntry(new ZipEntry(fileDto.getFileName()));
                while ((len = input.read(buf)) > 0) {
                    zipOutputStream.write(buf, 0, len);
                }
                zipOutputStream.closeEntry();
                input.close();
            }
            inputStream = new ByteArrayInputStream(bout.toByteArray());
            bout.flush();
            bout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    /**
     * 文件名生成
     *
     * @return 文件名
     */
    private static String generateFileName(String extension) {
        // 文件名称生成
        return generateName() + "." + extension;
    }
}
